package com.xiaotu.server.service;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.xiaotu.common.util.StringUtil;
import com.xiaotu.server.common.db.MyBatisDao;
import com.xiaotu.server.common.db.Page;

/**
 * @类名 BaseService
 * @日期 2014-12-17
 * @作者
 * @功能 业务层基类
 */
public abstract class BaseService
{
	@Autowired
	protected MyBatisDao myBatisDao;
	
	public int save(String key, Object object)
	{
		return myBatisDao.save(this.getKey() + "." + key, object);
	}
	
	public int delete(String key, Serializable id)
	{
		return myBatisDao.delete(this.getKey() + "." + key, id);
	}
	
	public int delete(String key, Object object)
	{
		return myBatisDao.delete(this.getKey() + "." + key, object);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T get(String key, Object params)
	{
		return (T) myBatisDao.get(this.getKey() + "." + key, params);
	}
	
	public <T> List<T> getList(String key)
	{
		return myBatisDao.getList(this.getKey() + "." + key);
	}
	
	public <T> List<T> getList(String key, Object params)
	{
		return myBatisDao.getList(this.getKey() + "." + key, params);
	}
	
	public <K, V> Map<K, V> getMap(String key, Object params, String mapKey)
	{
		return myBatisDao.getMap(this.getKey() + "." + key, params, mapKey);
	}
	
	public <K, V> Map<K, V> getMap(String key, String mapKey)
	{
		return myBatisDao.getMap(this.getKey() + "." + key, mapKey);
	}
	
	public int update(String key, Object params)
	{
		return myBatisDao.update(this.getKey() + "." + key, params);
	}
	
	public <T> List<T> queryPageList(String key, Object params, Page page)
	{
		return myBatisDao.queryPageList(this.getKey() + "." + key, params,
				page);
	}
	
	public Page queryPage(String key, Object params, Page page)
	{
		return myBatisDao.queryPage(this.getKey() + "." + key, params, page);
	}
	
	/**
	 * 获取mapper的namespace
	 * @return namespace
	 */
	protected abstract String getKey();
	
	public List<Map<String, Object>> formatResponseList(
			List<Map<String, Object>> list)
	{
		if (list == null || list.isEmpty())
			return list;
		for (Map<String, Object> map : list)
			this.formatResponseMap(map);
		return list;
	}
	
	protected void formatResponseMap(Map<String, Object> map)
	{
		for (Map.Entry<String, Object> entry : map.entrySet())
		{
			if (entry.getValue() == null
					|| StringUtils.isEmpty(entry.getValue() + ""))
				entry.setValue("暂无");
			else
				entry.setValue(StringUtil.getString(entry.getValue() + ""));
			
		}
	}
}
